﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using YiSha.Business.Cache;
using YiSha.Cache.Factory;
using YiSha.CodeGenerator.Model;
using YiSha.Data.Repository;
using YiSha.Entity.SystemManage;
using YiSha.Enums;
using YiSha.Enums.SystemManage;
using YiSha.Framework;
using YiSha.Model.Result.SystemManage;
using YiSha.Util;
using YiSha.Util.Model;

namespace YiSha.CodeGenerator.Template
{
    /// <summary>
    /// 代码生成模板
    /// </summary>
    public class NewSingleTableTemplate
    {
        #region GetBaseConfig 获取配置
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="path">当前系统路径</param>
        /// <param name="userName">操作人</param>
        /// <param name="tableName">表名</param>
        /// <param name="tableDescription">表描述</param>
        /// <param name="tableFieldList">表自动类型列表</param>
        /// <returns></returns>
        public BaseConfigModel GetBaseConfig(string path, string userName, string tableName, string tableDescription, List<string> tableFieldList)
        {
            path = GetProjectRootPath(path);
            // 页面显示字段数据量（默认显示2个字段）
            int defaultField = 2;
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            BaseConfigModel baseConfigModel = new BaseConfigModel();
            baseConfigModel.TableName = tableName;
            baseConfigModel.TableNameUpper = tableName;

            #region 文件配置模型
            baseConfigModel.FileConfig = new FileConfigModel();
            baseConfigModel.FileConfig.ClassPrefix = TableMappingHelper.GetClassNamePrefix(tableName);
            baseConfigModel.FileConfig.ClassDescription = tableDescription;
            baseConfigModel.FileConfig.CreateName = userName;
            baseConfigModel.FileConfig.CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");

            baseConfigModel.FileConfig.EntityName = string.Format("{0}Entity", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.EntityMapName = string.Format("{0}Map", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.EntityParamName = string.Format("{0}Param", baseConfigModel.FileConfig.ClassPrefix);
            //baseConfigModel.FileConfig.BusinessName = string.Format("{0}BLL", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.ServiceName = string.Format("{0}Service", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.ControllerName = string.Format("{0}Controller", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.PageIndexName = string.Format("{0}Index", baseConfigModel.FileConfig.ClassPrefix);
            baseConfigModel.FileConfig.PageFormName = string.Format("{0}Form", baseConfigModel.FileConfig.ClassPrefix);
            #endregion

            #region 输出模型          
            baseConfigModel.OutputConfig = new OutputConfigModel();
            baseConfigModel.OutputConfig.OutputModule = string.Empty;
            //实体类配置
            baseConfigModel.OutputConfig.OutputEntity = Path.Combine(path, "04 Entity",
                nameSpaceArr[0] + ".Entity");
            //查询类配置
            baseConfigModel.OutputConfig.OutputEntityParam = Path.Combine(path, "04 Entity",
            nameSpaceArr[0] + ".Model");
            //业务类配置
            baseConfigModel.OutputConfig.OutputBusiness = Path.Combine(path, "03 Business",
                nameSpaceArr[0] + ".Business");
            //业务类配置
            baseConfigModel.OutputConfig.OutputService = Path.Combine(path, "03 Business",
                nameSpaceArr[0] + ".Service");
            //web配置
            baseConfigModel.OutputConfig.OutputWeb = Path.Combine(path, "06 WebAreas",
                nameSpaceArr[0] + ".Areas.Core");
            string areasModule = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas");
            if (Directory.Exists(areasModule))
            {
                baseConfigModel.OutputConfig.ModuleList = Directory.GetDirectories(areasModule).Select(p => Path.GetFileName(p)).Where(p => p != "DemoManage").ToList();
            }
            else
            {
                baseConfigModel.OutputConfig.ModuleList = new List<string> { "TestManage" };
            }
            #endregion

            #region 首页视图模型
            baseConfigModel.PageIndex = new PageIndexModel();
            baseConfigModel.PageIndex.IsSearch = 1;
            baseConfigModel.PageIndex.IsPagination = 1;
            baseConfigModel.PageIndex.ButtonList = new List<string>();
            baseConfigModel.PageIndex.ColumnList = new List<string>();
            baseConfigModel.PageIndex.ColumnList.AddRange(tableFieldList.Take(defaultField));
            #endregion

            #region 添加页面视图模型
            baseConfigModel.PageForm = new PageFormModel();
            baseConfigModel.PageForm.ShowMode = 1;
            baseConfigModel.PageForm.FieldList = new List<string>();
            baseConfigModel.PageForm.FieldList.AddRange(tableFieldList.Take(defaultField));
            #endregion

            return baseConfigModel;
        }
        #endregion

        #region BuildEntity 生成实体类
        public string BuildEntity(BaseConfigModel baseConfigModel, DataTable dt)
        {
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using Newtonsoft.Json;");
            sb.AppendLine("using System.ComponentModel;");
            sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Framework;");
            sb.AppendLine();
            if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
            {
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Entity");
            }
            else
            {
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Entity." + baseConfigModel.OutputConfig.OutputModule);
            }
            sb.AppendLine("{");

            SetClassDescription("实体类", baseConfigModel, sb);

            sb.AppendLine("    [Table(\"" + baseConfigModel.TableName + "\")]");
            sb.AppendLine("    [SqlSugar.SugarTable(\"" + baseConfigModel.TableName + "\")]");
            sb.AppendLine("    public class " + baseConfigModel.FileConfig.EntityName + " : " + GetBaseEntity(dt));
            sb.AppendLine("    {");

            string column = string.Empty;
            string remark = string.Empty;
            string datatype = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                column = dr["TableColumn"].ToString();
                if (BaseField.BaseFieldList.Where(p => p == column).Any())
                {
                    // 基础字段不需要生成，继承合适的BaseEntity即可。
                    continue;
                }

                remark = dr["Remark"].ToString();
                datatype = dr["Datatype"].ToString();
                //
                datatype = TableMappingHelper.GetPropertyDatatype(datatype);

                sb.AppendLine("        /// <summary>");
                sb.AppendLine("        /// " + remark);
                sb.AppendLine("        /// </summary>");
                sb.AppendLine("        /// <returns></returns>");
                sb.AppendLine("        [Description(\"" + remark + "\")]");

                switch (datatype)
                {
                    case "long?":
                        sb.AppendLine("        [JsonConverter(typeof(StringJsonConverter))]");
                        break;

                    case "DateTime?":
                        sb.AppendLine("        [JsonConverter(typeof(DateTimeJsonConverter))]");
                        break;
                }
                sb.AppendLine("        public " + datatype + " " + column + " { get; set; }");
            }
            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }
        #endregion

        #region BuildEntityParam 生成请求model
        /// <summary>
        /// 生成请求model
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <returns></returns>
        public string BuildEntityParam(BaseConfigModel baseConfigModel, List<TableFieldInfo> tableField)
        {
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using Newtonsoft.Json;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util;");
            sb.AppendLine();
            if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
            {
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Model.Param");
            }
            else
            {
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Model.Param." + baseConfigModel.OutputConfig.OutputModule);
            }
            sb.AppendLine("{");

            SetClassDescription("实体查询类", baseConfigModel, sb);

            sb.AppendLine("    public class " + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam"));
            sb.AppendLine("    {");
            //根据搜索生成请求字段
            if (baseConfigModel.PageIndex.IsSearch == 1)
            {
                //获取字段类型
                string fieldName = TextHelper.GetCustomValue(baseConfigModel.PageIndex.ColumnList.FirstOrDefault(), "fieldName");
                //获取字段信息
                var name = tableField.Where(w => w.TableColumn == fieldName).FirstOrDefault();
                //
                var datatype = TableMappingHelper.GetPropertyDatatype(name.Datatype);
                sb.AppendLine("        public " + datatype + " " + fieldName + " { get; set; }");
            }
            sb.AppendLine("    }");
            sb.AppendLine("}");

            return sb.ToString();
        }
        #endregion

        #region BuildService 生成服务类
        /// <summary>
        /// 生成服务类
        /// </summary>
        /// <param name="baseConfigModel">基础配置模型</param>
        /// <param name="dt">表信息</param>
        /// <returns></returns>
        public string BuildService(BaseConfigModel baseConfigModel, DataTable dt, List<TableFieldInfo> tableField)
        {
            string baseEntity = GetBaseEntity(dt);
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            StringBuilder sb = new StringBuilder();
            string method = string.Empty;
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Linq;");
            sb.AppendLine("using System.Text;");
            sb.AppendLine("using System.Data.Common;");
            sb.AppendLine("using System.Linq.Expressions;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Threading.Tasks;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Enums;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util.Model;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Data;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Data.Repository;");

            if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
            {
                sb.AppendLine("using " + nameSpaceArr[0] + ".Entity;");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Model.Param;");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Service");
            }
            else
            {
                sb.AppendLine("using " + nameSpaceArr[0] + ".Entity." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Model.Param." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Service." + baseConfigModel.OutputConfig.OutputModule);
            }
            sb.AppendLine("{");

            SetClassDescription("服务类", baseConfigModel, sb);

            sb.AppendLine("    public class " + baseConfigModel.FileConfig.ServiceName + " :  RepositoryFactory");
            sb.AppendLine("    {");
            sb.AppendLine("        #region 获取数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 获取数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns>返回所有列表信息</returns>");
            sb.AppendLine("        public async Task<TData<List<" + baseConfigModel.FileConfig.EntityName + ">>> GetList(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param)");
            sb.AppendLine("        {");
            sb.AppendLine("            var obj = new TData<List<" + baseConfigModel.FileConfig.EntityName + ">>();");
            sb.AppendLine("            var expression = ListFilter(param);");
            sb.AppendLine("            //查询数据");
            sb.AppendLine("            var list =  SqlSugarAdapters.GetList(expression);");
            sb.AppendLine("            obj.Data = list;");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 分页获取数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns>返回分页列表信息</returns>");
            sb.AppendLine("        public async Task<TData<List<" + baseConfigModel.FileConfig.EntityName + ">>> GetPageList(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param, Pagination pagination)");
            sb.AppendLine("        {");
            sb.AppendLine("            var obj = new TData<List<" + baseConfigModel.FileConfig.EntityName + ">>();");
            sb.AppendLine("            var expression = ListFilter(param);");
            sb.AppendLine("            //查询数据");
            sb.AppendLine("            var list=  SqlSugarAdapters.GetPager(expression, pagination);");
            sb.AppendLine("            //获取数据及总条数");
            sb.AppendLine("            obj.Total = list.Item1;");
            sb.AppendLine("            obj.Data = list.Item2;");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 获取数据详情");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns>返回数据详情</returns>");
            sb.AppendLine("        public async Task<TData<" + baseConfigModel.FileConfig.EntityName + ">> GetEntity(string id)");
            sb.AppendLine("        {");
            sb.AppendLine("            var entity= SqlSugarAdapters.GetEntity<" + baseConfigModel.FileConfig.EntityName + ">(s=>s.Id==id);");
            sb.AppendLine("            return new TData<" + baseConfigModel.FileConfig.EntityName + "> { Data = entity };");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 提交数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 保存数据");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns></returns>");
            sb.AppendLine("        public async Task<TData> SaveForm(" + baseConfigModel.FileConfig.EntityName + " entity)");
            sb.AppendLine("        {");
            sb.AppendLine("            var obj = new TData();");
            sb.AppendLine("            try");
            sb.AppendLine("            {");
            sb.AppendLine("                if (entity.Id.IsEmpty())");
            sb.AppendLine("                {");
            sb.AppendLine("                    " + GetSaveFormCreate(baseEntity));
            sb.AppendLine("                    SqlSugarAdapters.Insert(entity);");
            sb.AppendLine("                }");
            sb.AppendLine("                else");
            sb.AppendLine("                {");
            sb.AppendLine("                    " + GetSaveFormModify(baseEntity));
            sb.AppendLine("                    SqlSugarAdapters.Update(entity);");
            sb.AppendLine("                }");
            sb.AppendLine("            }");
            sb.AppendLine("            catch (Exception ex)");
            sb.AppendLine("            {");
            sb.AppendLine("                obj.Msg = ex.Message;");
            sb.AppendLine("                obj.MsgCode = MsgCode.Fail;");
            sb.AppendLine("            }");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 删除数据（物理删除）");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns></returns>");
            sb.AppendLine("        public async Task<TData> DeleteForm(List<string> ids)");
            sb.AppendLine("        {");
            sb.AppendLine("            var obj = new TData();");
            sb.AppendLine("            try");
            sb.AppendLine("            {");
            sb.AppendLine("                SqlSugarAdapters.Delete<" + baseConfigModel.FileConfig.EntityName + ">(d => ids.Contains(d.Id));");
            sb.AppendLine("            }");
            sb.AppendLine("            catch (Exception ex)");
            sb.AppendLine("            {");
            sb.AppendLine("                obj.Msg = ex.Message;");
            sb.AppendLine("                obj.MsgCode = MsgCode.Fail;");
            sb.AppendLine("            }");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 私有方法");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 查询表达式");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        /// <returns></returns>");
            sb.AppendLine("        private Expression<Func<" + baseConfigModel.FileConfig.EntityName + ", bool>> ListFilter(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param)");
            sb.AppendLine("        {");
            sb.AppendLine("            var expression = ExtLinq.True<" + baseConfigModel.FileConfig.EntityName + ">();");
            //根据搜索生成请求字段
            if (baseConfigModel.PageIndex.IsSearch == 1)
            {
                //获取字段类型
                string fieldName = TextHelper.GetCustomValue(baseConfigModel.PageIndex.ColumnList.FirstOrDefault(), "fieldName");
                var name = tableField.Where(w => w.TableColumn == fieldName).FirstOrDefault();
                //获取字段信息
                sb.AppendLine("            if (param != null)");
                sb.AppendLine("            {");
                sb.AppendLine("                if (!param." + name.TableColumn + ".IsEmpty())");
                sb.AppendLine("                {");
                sb.AppendLine("                    expression = expression.And(t => t." + name.TableColumn + " == param." + name.TableColumn + ");");
            }
            sb.AppendLine("                }");
            sb.AppendLine("            }");
            sb.AppendLine("            return expression;");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");

            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }
        #endregion

        #region BuildBusiness 生成业务层（当前框架未使用）
        /// <summary>
        /// 生成业务层（当前框架未使用）
        /// </summary>
        /// <param name="baseConfigModel">基础模型</param>
        /// <returns></returns>
        public string BuildBusiness(BaseConfigModel baseConfigModel)
        {
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Linq;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Threading.Tasks;");
            sb.AppendLine("using " + nameSpace[0] + ".Util;");
            sb.AppendLine("using " + nameSpace[0] + ".Enums;");
            sb.AppendLine("using " + nameSpace[0] + ".Util.Model;");
            if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
            {
                sb.AppendLine("using " + nameSpace[0] + ".Entity;");
                sb.AppendLine("using " + nameSpace[0] + ".Model.Param;");
                sb.AppendLine("using " + nameSpace[0] + ".Service;");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpace[0] + ".Business");
            }
            else
            {
                sb.AppendLine("using " + nameSpace[0] + ".Entity." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine("using " + nameSpace[0] + ".Model.Param." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine("using " + nameSpace[0] + ".Service." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpace[0] + ".Business." + baseConfigModel.OutputConfig.OutputModule);
            }
            sb.AppendLine("{");

            SetClassDescription("业务类", baseConfigModel, sb);

            sb.AppendLine("    public class " + baseConfigModel.FileConfig.BusinessName);
            sb.AppendLine("    {");
            sb.AppendLine("        #region 服务");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// " + baseConfigModel.FileConfig.ClassDescription + "服务");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public " + baseConfigModel.FileConfig.ServiceName + " " + baseConfigModel.FileConfig.ServiceName + " { get; set; } ");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 获取数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 查询数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public async Task<TData<List<" + baseConfigModel.FileConfig.EntityName + ">>> GetList(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<List<" + baseConfigModel.FileConfig.EntityName + ">> obj = new TData<List<" + baseConfigModel.FileConfig.EntityName + ">>();");
            sb.AppendLine("            obj.Data = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetList(param);");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 分页查询数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public async Task<TData<List<" + baseConfigModel.FileConfig.EntityName + ">>> GetPageList(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param, Pagination pagination)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<List<" + baseConfigModel.FileConfig.EntityName + ">> obj = new TData<List<" + baseConfigModel.FileConfig.EntityName + ">>();");
            sb.AppendLine("            obj.Data = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetPageList(param, pagination);");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 查询详情");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public async Task<TData<" + baseConfigModel.FileConfig.EntityName + ">> GetEntity(string id)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<" + baseConfigModel.FileConfig.EntityName + "> obj = new TData<" + baseConfigModel.FileConfig.EntityName + ">();");
            sb.AppendLine("            obj.Data = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetEntity(id);");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 提交数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 保存数据");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public async Task<TData> SaveForm(" + baseConfigModel.FileConfig.EntityName + " entity)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData obj = new TData();");
            sb.AppendLine("            await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".SaveForm(entity);");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 删除数据");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public async Task<TData> DeleteForm(List<string> ids)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData obj = new TData();");
            sb.AppendLine("            await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".DeleteForm(ids);");
            sb.AppendLine("            return obj;");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 私有方法");
            sb.AppendLine("        #endregion");

            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }
        #endregion

        #region BuildController 生成控制器
        /// <summary>
        /// 生成控制器
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <returns></returns>
        public string BuildController(BaseConfigModel baseConfigModel)
        {
            string modulePrefix = GetModulePrefix(baseConfigModel);
            string classPrefix = baseConfigModel.FileConfig.ClassPrefix.ToLower();
            //获取命名空间
            var nameSpace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            var nameSpaceArr = nameSpace.Split('.');
            //
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Threading.Tasks;");
            sb.AppendLine("using System.Linq;");
            sb.AppendLine("using System.Web;");
            sb.AppendLine("using Microsoft.AspNetCore.Mvc;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Entity;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Util.Model;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Basics;");
            sb.AppendLine("using " + nameSpaceArr[0] + ".Model;");
            if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
            {
                sb.AppendLine("using " + nameSpaceArr[0] + ".Entity;");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Service;");
                //sb.AppendLine("using YiSha.Business;");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Model.Param;");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Areas.Core.Controllers");
            }
            else
            {
                sb.AppendLine("using " + nameSpaceArr[0] + ".Entity." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Service." + baseConfigModel.OutputConfig.OutputModule + ";");
                //sb.AppendLine("using YiSha.Business." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine("using " + nameSpaceArr[0] + ".Model.Param." + baseConfigModel.OutputConfig.OutputModule + ";");
                sb.AppendLine();
                sb.AppendLine("namespace " + nameSpaceArr[0] + ".Areas.Core." + baseConfigModel.OutputConfig.OutputModule + ".Controllers");
            }
            sb.AppendLine("{");

            SetClassDescription("控制器类", baseConfigModel, sb);
            sb.AppendLine("    [Area(\"" + baseConfigModel.OutputConfig.OutputModule + "\")]");
            sb.AppendLine("    public class " + baseConfigModel.FileConfig.ControllerName + " :  BaseController");
            sb.AppendLine("    {");
            sb.AppendLine("        public " + baseConfigModel.FileConfig.ServiceName + " " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + " { get; set; }");
            sb.AppendLine();
            sb.AppendLine("        #region 视图功能");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// " + baseConfigModel.FileConfig.ClassDescription + "首页");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [AuthorizeFilter(\"" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "view") + "\")]");
            sb.AppendLine("        public ActionResult " + baseConfigModel.FileConfig.PageIndexName + "()");
            sb.AppendLine("        {");
            sb.AppendLine("            return View();");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// " + baseConfigModel.FileConfig.ClassDescription + "添加/修改");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        public ActionResult " + baseConfigModel.FileConfig.PageFormName + "()");
            sb.AppendLine("        {");
            sb.AppendLine("            return View();");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 获取数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 获取数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [HttpGet]");
            sb.AppendLine("        [AuthorizeFilter(\"" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "search") + "\")]");
            sb.AppendLine("        public async Task<ActionResult> GetListJson(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<List<" + baseConfigModel.FileConfig.EntityName + ">> obj = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetList(param);");
            sb.AppendLine("            return Json(obj);");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 分页获取数据列表");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [HttpGet]");
            sb.AppendLine("        [AuthorizeFilter(\"" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "search") + "\")]");
            sb.AppendLine("        public async Task<ActionResult> GetPageListJson(" + baseConfigModel.FileConfig.EntityParamName.Replace("Param", "ListParam") + " param, Pagination pagination)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<List<" + baseConfigModel.FileConfig.EntityName + ">> obj = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetPageList(param, pagination);");
            sb.AppendLine("            return Json(obj);");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 获取详情");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [HttpGet]");
            sb.AppendLine("        public async Task<ActionResult> GetFormJson(string id)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData<" + baseConfigModel.FileConfig.EntityName + "> obj = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".GetEntity(id);");
            sb.AppendLine("            return Json(obj);");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine();
            sb.AppendLine("        #region 提交数据");
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 保存数据");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [HttpPost]");
            sb.AppendLine("        [AuthorizeFilter(\"" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "add") + "," + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "edit") + "\")]");
            sb.AppendLine("        public async Task<ActionResult> SaveFormJson(" + baseConfigModel.FileConfig.EntityName + " entity)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData obj = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".SaveForm(entity);");
            sb.AppendLine("            return Json(obj);");
            sb.AppendLine("        }");
            sb.AppendLine();
            sb.AppendLine("        /// <summary>");
            sb.AppendLine("        /// 删除数据（物理删除）");
            sb.AppendLine("        /// </summary>");
            sb.AppendLine("        [HttpPost]");
            sb.AppendLine("        [AuthorizeFilter(\"" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "delete") + "\")]");
            sb.AppendLine("        public async Task<ActionResult> DeleteFormJson(List<string> ids)");
            sb.AppendLine("        {");
            sb.AppendLine("            TData obj = await " + TableMappingHelper.FirstLetterLowercase(baseConfigModel.FileConfig.ServiceName) + ".DeleteForm(ids);");
            sb.AppendLine("            return Json(obj);");
            sb.AppendLine("        }");
            sb.AppendLine("        #endregion");
            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }
        #endregion

        #region BuildIndex 生成首页视图
        /// <summary>
        /// 生成首页视图
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <param name="tableField">表字段信息</param>
        /// <returns></returns>
        public string BuildIndex(BaseConfigModel baseConfigModel, List<TableFieldInfo> tableField)
        {
            #region 初始化集合
            if (baseConfigModel.PageIndex.ButtonList == null)
            {
                baseConfigModel.PageIndex.ButtonList = new List<string>();
            }
            if (baseConfigModel.PageIndex.ColumnList == null)
            {
                baseConfigModel.PageIndex.ColumnList = new List<string>();
            }
            #endregion

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("@{");
            sb.AppendLine("    Layout = \"~/Views/Shared/_Index.cshtml\";");
            sb.AppendLine(" }");
            sb.AppendLine("<div class=\"container-div\">");
            sb.AppendLine("    <div class=\"row\">");

            #region 是否显示搜索
            if (baseConfigModel.PageIndex.IsSearch == 1)
            {
                string fieldName = TextHelper.GetCustomValue(baseConfigModel.PageIndex.ColumnList.FirstOrDefault(), "fieldName");
                //获取字段信息
                var name = tableField.Where(w => w.TableColumn == fieldName).FirstOrDefault();
                //
                string fieldNameLower = TableMappingHelper.FirstLetterLowercase(fieldName);
                sb.AppendLine("        <div class=\"col-sm-12 search-collapse\">");
                sb.AppendLine("            <form id=\"post-form\">");
                sb.AppendLine("                <div class=\"select-list\">");
                sb.AppendLine("                    <ul>");
                sb.AppendLine("                        <li>");
                sb.AppendLine("                        " + (name.IsEmpty() ? fieldName : name.Remark) + "：<input id=\"" + fieldNameLower + "\" name=\"" + fieldName + "\" type=\"text\" />");
                sb.AppendLine("                        </li>");
                sb.AppendLine("                        <li>");
                sb.AppendLine("                             <a class=\"btn btn-primary btn-rounded btn-sm\" onclick=\"$.table.search()\"><i class=\"fa fa-search\"></i>&nbsp;搜索</a>");
                sb.AppendLine("                             <a class=\"btn btn-warning btn-rounded btn-sm\" onclick=\"$.form.reset()\"><i class=\"fa fa-refresh\"></i>&nbsp;重置</a>");
                sb.AppendLine("                        </li>");
                sb.AppendLine("                    </ul>");
                sb.AppendLine("                </div>");
                sb.AppendLine("            </form>");
                sb.AppendLine("        </div>");
            }
            #endregion

            #region 是否显示工具栏
            if (baseConfigModel.PageIndex.ButtonList.Where(p => p != "btnSearch").Any())
            {
                sb.AppendLine("        <div class=\"btn-group-sm\" id=\"toolbar\" role=\"group\">");
                if (baseConfigModel.PageIndex.ButtonList.Where(p => p == "btnAdd").Any())
                {
                    sb.AppendLine("            <a class=\"btn btn-success\" onclick=\"$.operate.add()\"><i class=\"fa fa-plus\"></i> 新增</a>");
                }
                if (baseConfigModel.PageIndex.ButtonList.Where(p => p == "btnEdit").Any())
                {
                    sb.AppendLine("            <a class=\"btn btn-primary single disabled\" onclick=\"$.operate.edit()\"><i class=\"fa fa-edit\"></i> 修改</a>");
                }
                if (baseConfigModel.PageIndex.ButtonList.Where(p => p == "btnDelete").Any())
                {
                    sb.AppendLine("            <a class=\"btn btn-danger multiple disabled\" onclick=\"$.operate.removeAll()\" ><i class=\"fa fa-remove\"></i> 删除</a>");
                }
                if (baseConfigModel.PageIndex.ButtonList.Where(p => p == "btnExcel").Any())
                {
                    sb.AppendLine("            <a class=\"btn btn-warning\" onclick=\"$.table.exportExcel()\"><i class=\"fa fa-download\"></i> 导出</a>");
                }
                sb.AppendLine("       </div>");
            }
            #endregion
            //
            sb.AppendLine("         <div class=\"col-sm-12 select-table table-striped\">");
            sb.AppendLine("            <table id=\"gridTable\"></table>");
            sb.AppendLine("        </div>");
            sb.AppendLine("    </div>");
            sb.AppendLine("</div>");
            sb.AppendLine("");
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("    $(function () {");
            sb.AppendLine("    var options = {");
            sb.AppendLine("        id: \"gridTable\",     //数据表格id");
            sb.AppendLine("        url: \"/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/GetPageListJson\",    //分页查询数据地址");
            sb.AppendLine("        createUrl: \"/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.ClassPrefix + "Form\",            //新增数据视图页");
            sb.AppendLine("        updateUrl: \"/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.ClassPrefix + "Form\",            //修改数据视图页");
            sb.AppendLine("        removeUrl: \"/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/DeleteFormJson\",            //删除数据地址（批量删除）");
            sb.AppendLine("        modalName: \"" + baseConfigModel.FileConfig.ClassDescription + "\",");
            if (baseConfigModel.PageIndex.ColumnList.Where(w => w == "BaseCreateTime").FirstOrDefault().IsEmpty())
            {
                sb.AppendLine("        sortName:'baseCreateTime',     //排序字段");
            }
            else
            {
                sb.AppendLine("        sortName:'id',             //排序字段");
            }
            sb.AppendLine("        sortOrder:'desc',              //排序类型");
            if (baseConfigModel.PageIndex.IsPagination == 0)
            {
                sb.AppendLine("    pagination: false,             //是否显示分页");
            }
            sb.AppendLine("        columns: [");
            sb.AppendLine("            { checkbox: true, visible: true },");
            sb.AppendLine("            { field: 'id', title: 'id', visible: false },");
            foreach (string column in baseConfigModel.PageIndex.ColumnList)
            {
                var field = TableMappingHelper.FirstLetterLowercase(column);
                //获取表字段信息
                var tableColumn = tableField.Where(w => w.TableColumn == column).FirstOrDefault();
                sb.AppendLine("            { field: '" + field + "', title: '" + (tableColumn.IsEmpty() ? field : tableColumn.Remark) + "' },");
            }
            sb.AppendLine("         ],");
            sb.AppendLine("         onClickRow: function (row, element) {");
            sb.AppendLine("             element[0].firstElementChild.firstElementChild.click();");
            sb.AppendLine("         }");
            sb.AppendLine("     };");
            sb.AppendLine("     $.table.init(options);");
            sb.AppendLine(" });");
            sb.AppendLine("");
            sb.AppendLine("");

            sb.AppendLine("</script>");
            return sb.ToString();
        }
        #endregion

        #region BuildForm 生成添加页视图
        /// <summary>
        /// 生成添加页视图
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <returns></returns>
        public string BuildForm(BaseConfigModel baseConfigModel, List<TableFieldInfo> tableField)
        {
            #region 初始化集合
            if (baseConfigModel.PageForm.FieldList == null)
            {
                baseConfigModel.PageForm.FieldList = new List<string>();
            }
            #endregion
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("@{");
            sb.AppendLine("    Layout = \"~/Views/Shared/_FormWhite.cshtml\";");
            sb.AppendLine("}");
            sb.AppendLine("");
            sb.AppendLine("<div class=\"wrapper animated fadeInRight\">");
            sb.AppendLine("    <form id=\"form\" class=\"form-horizontal m\">");
            sb.AppendLine("    <input type=\"hidden\" id=\"id\" name=\"id\" />");

            #region 表单控件
            if (baseConfigModel.PageForm.FieldList.Count > 0)
            {
                string field = string.Empty;
                string fieldLower = string.Empty;
                switch (baseConfigModel.PageForm.ShowMode)
                {
                    case 1:
                        for (int i = 0; i < baseConfigModel.PageForm.FieldList.Count; i++)
                        {
                            field = baseConfigModel.PageForm.FieldList[i];
                            //获取字段信息
                            var col = tableField.Where(w => w.TableColumn == field).FirstOrDefault();
                            fieldLower = TableMappingHelper.FirstLetterLowercase(field);

                            sb.AppendLine("        <div class=\"form-group\">");
                            sb.AppendLine("            <label class=\"col-sm-3 control-label \">" + col.Remark + (i == 0 ? "<font class=\"red\"> *</font>" : string.Empty) + "</label>");
                            sb.AppendLine("            <div class=\"col-sm-8\">");
                            sb.AppendLine("                <input id=\"" + fieldLower + "\" name=\"" + field + "\" type=\"text\" class=\"form-control\" />");
                            sb.AppendLine("            </div>");
                            sb.AppendLine("        </div>");
                        }
                        break;

                    case 2:
                        for (int i = 0; i < baseConfigModel.PageForm.FieldList.Count; i++)
                        {
                            field = baseConfigModel.PageForm.FieldList[i];
                            //获取字段信息
                            var col = tableField.Where(w => w.TableColumn == field).FirstOrDefault();
                            fieldLower = TableMappingHelper.FirstLetterLowercase(field);

                            if (i % 2 == 0)
                            {
                                sb.AppendLine("        <div class=\"form-group\">");
                            }

                            sb.AppendLine("            <label class=\"col-sm-2 control-label \">" + col.Remark + "<font class=\"red\"> *</font></label>");
                            sb.AppendLine("            <div class=\"col-sm-4\">");
                            sb.AppendLine("                <input id=\"" + field + "\" name=\"" + field + "\" type=\"text\" class=\"form-control\" />");
                            sb.AppendLine("            </div>");

                            if (i % 2 == 1)
                            {
                                sb.AppendLine("        </div>");
                            }
                        }
                        break;
                }
            }
            #endregion

            sb.AppendLine("    </form>");
            sb.AppendLine("</div>");
            sb.AppendLine("");
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("    $(function () {");
            sb.AppendLine("");
            sb.AppendLine("        $('#form').validate({");
            sb.AppendLine("            rules: {");
            sb.AppendLine("                " + TextHelper.GetCustomValue(TableMappingHelper.FirstLetterLowercase(baseConfigModel.PageForm.FieldList.FirstOrDefault()), "fieldName") + ": { required: true }");
            sb.AppendLine("            }");
            sb.AppendLine("        });");
            sb.AppendLine("");
            sb.AppendLine("        getForm();");
            sb.AppendLine("");
            sb.AppendLine("    });");
            sb.AppendLine("");
            sb.AppendLine("    /**表单初始化**/");
            sb.AppendLine("    function getForm() {");
            sb.AppendLine("        //修改赋值使用");
            sb.AppendLine("        var editData = storage.get(\"editData\");");
            sb.AppendLine("        if (editData != null && editData.length > 0) {");
            sb.AppendLine("            var data = JSON.parse(editData);");
            sb.AppendLine("            //表单赋值");
            sb.AppendLine("            $(\"#form\").setWebControls(data);");
            sb.AppendLine("        }");
            sb.AppendLine("        else {");
            sb.AppendLine("            //表单初始化");
            sb.AppendLine("            var defaultData = {};");
            sb.AppendLine("            $('#form').setWebControls(defaultData);");
            sb.AppendLine("        }");
            sb.AppendLine("    }");
            sb.AppendLine("");
            sb.AppendLine("    /**提交数据**/");
            sb.AppendLine("    function submitForm() {");
            sb.AppendLine("        if ($('#form').validate().form()) {");
            sb.AppendLine("            $.operate.save(\"/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/SaveFormJson\",$(\"#form\").getWebControls());");
            sb.AppendLine("        }");
            sb.AppendLine("    }");
            sb.AppendLine("</script>");
            sb.AppendLine("");
            return sb.ToString();
        }
        #endregion

        #region BuildMenu 生成菜单
        /// <summary>
        /// 生成菜单
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <returns></returns>
        public string BuildMenu(BaseConfigModel baseConfigModel)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine();
            sb.AppendLine("  菜单路径:" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName);
            sb.AppendLine();
            string modulePrefix = GetModulePrefix(baseConfigModel);
            string classPrefix = baseConfigModel.FileConfig.ClassPrefix.ToLower();
            sb.AppendLine("  页面显示权限：" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "view"));
            sb.AppendLine();
            List<KeyValue> list = GetButtonAuthorizeList();

            if (baseConfigModel.PageIndex.IsSearch == 1)
            {
                KeyValue button = list.Where(p => p.Key == "btnSearch").FirstOrDefault();
                sb.AppendLine("  按钮" + button.Description + "权限：" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, button.Value));
            }
            foreach (string btn in baseConfigModel.PageIndex.ButtonList)
            {
                KeyValue button = list.Where(p => p.Key == btn).FirstOrDefault();
                sb.AppendLine("  按钮" + button.Description + "权限：" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, button.Value));
            }
            sb.AppendLine();
            return sb.ToString();
        }
        #endregion

        #region CreateCode  创建代码(创建对应的类)
        /// <summary>
        /// 创建代码
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <param name="code"></param>
        /// <param name="tableField">表字段信息</param>
        /// <returns></returns>
        public async Task<List<KeyValue>> CreateCode(BaseConfigModel baseConfigModel, string code, List<TableInfo> tableField)
        {
            List<KeyValue> result = new List<KeyValue>();
            JObject param = code.ToJObject();

            #region 创建实体类
            if (!string.IsNullOrEmpty(param["codeEntity"].ParseToString()) && baseConfigModel.IsGenerateEntity == 1)
            {
                string codeEntity = HttpUtility.HtmlDecode(param["codeEntity"].ToString());
                string codePath = string.Empty;
                if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.FileConfig.EntityName + ".cs");
                }
                else
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityName + ".cs");
                }
                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeEntity);
                    result.Add(new KeyValue { Key = "实体类", Value = codePath });
                }
            }
            #endregion

            #region 创建实体查询类
            if (!param["codeEntityParam"].IsEmpty())
            {
                string codeListEntity = HttpUtility.HtmlDecode(param["codeEntityParam"].ToString());
                string codePath = Path.Combine(baseConfigModel.OutputConfig.OutputEntityParam, "Param", baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityParamName + ".cs");
                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeListEntity);
                    result.Add(new KeyValue { Key = "实体查询类", Value = codePath });
                }
            }
            #endregion

            #region 创建服务类
            if (!param["codeService"].IsEmpty() && baseConfigModel.IsGenerateService == 1)
            {
                string codeService = HttpUtility.HtmlDecode(param["codeService"].ToString());
                string codePath = Path.Combine(baseConfigModel.OutputConfig.OutputService, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.ServiceName + ".cs");
                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeService);
                    result.Add(new KeyValue { Key = "服务类", Value = codePath });
                }
            }
            #endregion

            #region 创建业务类（当前未使用）
            //if (!param["CodeBusiness"].IsEmpty())
            //{
            //    string codeBusiness = HttpUtility.HtmlDecode(param["CodeBusiness"].ToString());
            //    string codePath = Path.Combine(baseConfigModel.OutputConfig.OutputBusiness, "YiSha.Business", baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.BusinessName + ".cs");
            //    if (!File.Exists(codePath))
            //    {
            //        FileHelper.CreateFile(codePath, codeBusiness);
            //        result.Add(new KeyValue { Key = "业务类", Value = codePath });
            //    }
            //}
            #endregion

            #region 创建控制器
            if (!param["codeController"].IsEmpty())
            {
                string codeController = HttpUtility.HtmlDecode(param["codeController"].ToString());
                string codePath = string.Empty;
                if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, baseConfigModel.OutputConfig.OutputModule, "Controllers", baseConfigModel.FileConfig.ControllerName + ".cs");
                }
                else
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Controllers", baseConfigModel.FileConfig.ControllerName + ".cs");
                }
                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeController);
                    result.Add(new KeyValue { Key = "控制器", Value = codePath });
                }
            }
            #endregion

            #region 创建列表页
            if (!param["codeIndex"].IsEmpty())
            {
                string codeIndex = HttpUtility.HtmlDecode(param["codeIndex"].ToString());
                string codePath = string.Empty;
                if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageIndexName + ".cshtml");
                }
                else
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageIndexName + ".cshtml");
                }

                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeIndex);
                    result.Add(new KeyValue { Key = "列表页", Value = codePath });
                }

                // 生成菜单
                RepositoryFactory repositoryFactory = new RepositoryFactory();
                List<KeyValue> buttonAuthorizeList = GetButtonAuthorizeList();
                string menuUrl = baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName;
                string modulePrefix = GetModulePrefix(baseConfigModel);
                string classPrefix = baseConfigModel.FileConfig.ClassPrefix.ToLower();
                //获取数据库表信息
                var tables = tableField.Where(w => w.TableName == baseConfigModel.TableName).FirstOrDefault();
                MenuEntity menuEntity = new MenuEntity
                {
                    MenuName = baseConfigModel.FileConfig.ClassDescription.IsEmpty() ? tables.Remark : baseConfigModel.FileConfig.ClassDescription,
                    MenuUrl = "/" + menuUrl,
                    ParentName = "主目录",
                    ParentId = "0",
                    MenuType = (int)MenuTypeEnum.Menu,
                    Authorize = string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, "view")
                };
                TData obj = await AddMenu(repositoryFactory, menuEntity);
                if (obj.MsgCode == MsgCode.Success)
                {
                    result.Add(new KeyValue { Key = "菜单(刷新页面可见)", Value = menuUrl });
                    if (baseConfigModel.PageIndex.IsSearch == 1)
                    {
                        // 按钮搜索权限
                        KeyValue button = buttonAuthorizeList.Where(p => p.Key == "btnSearch").FirstOrDefault();
                        MenuEntity buttonEntity = new MenuEntity
                        {
                            ParentId = menuEntity.Id,
                            MenuName = baseConfigModel.FileConfig.ClassDescription + button.Description,
                            MenuType = (int)MenuTypeEnum.Button,
                            Authorize = string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, button.Value)
                        };
                        await AddMenu(repositoryFactory, buttonEntity);
                    }
                    foreach (string btn in baseConfigModel.PageIndex.ButtonList)
                    {
                        KeyValue button = buttonAuthorizeList.Where(p => p.Key == btn).FirstOrDefault();
                        MenuEntity buttonEntity = new MenuEntity
                        {
                            ParentId = menuEntity.Id,
                            MenuName = baseConfigModel.FileConfig.ClassDescription + button.Description,
                            MenuType = (int)MenuTypeEnum.Button,
                            Authorize = string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, button.Value)
                        };
                        await AddMenu(repositoryFactory, buttonEntity);
                    }
                    new MenuCache().Remove();
                }
            }
            #endregion

            #region 创建表单页
            if (!param["codeForm"].IsEmpty())
            {
                string codeSave = HttpUtility.HtmlDecode(param["codeForm"].ToString());
                string codePath = string.Empty;
                if (baseConfigModel.OutputConfig.OutputModule.IsEmpty())
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageFormName + ".cshtml");
                }
                else
                {
                    codePath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageFormName + ".cshtml");
                }

                if (!File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeSave);
                    result.Add(new KeyValue { Key = "表单页", Value = codePath });
                }
            }
            #endregion

            return result;
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="repositoryFactory"></param>
        /// <param name="menuEntity"></param>
        /// <returns></returns>
        private async Task<TData> AddMenu(RepositoryFactory repositoryFactory, MenuEntity menuEntity)
        {
            TData obj = new TData() { MsgCode = MsgCode.Success };
            try
            {
                IEnumerable<MenuEntity> menuList = await repositoryFactory.BaseRepository().FindList<MenuEntity>();
                if (!menuList.Where(p => p.MenuName == menuEntity.MenuName && p.Authorize == menuEntity.Authorize).Any())
                {
                    menuEntity.MenuSort = menuList.Max(p => p.MenuSort) + 1;
                    menuEntity.MenuStatus = 1;
                    await menuEntity.Create();
                    await repositoryFactory.BaseRepository().Insert(menuEntity);
                }
            }
            catch (Exception ex)
            {
                obj.Msg = ex.Message;
                obj.MsgCode = MsgCode.Fail;
            }
            return obj;
        }
        #endregion

        #region 私有方法
        #region GetProjectRootPath 获取项目根路径
        /// <summary>
        /// 获取项目根路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetProjectRootPath(string path)
        {
            path = path.ParseToString();
            path = path.Trim('\\');
            if (GlobalContext.SystemConfig.Debug)
            {
                // 向上找二级
                path = Directory.GetParent(path).FullName;
                path = Directory.GetParent(path).FullName;
            }
            return path;
        }
        #endregion

        #region SetClassDescription 设置类描述
        /// <summary>
        /// 设置类描述
        /// </summary>
        /// <param name="type"></param>
        /// <param name="baseConfigModel"></param>
        /// <param name="sb"></param>
        private void SetClassDescription(string type, BaseConfigModel baseConfigModel, StringBuilder sb)
        {
            sb.AppendLine("    /// <summary>");
            sb.AppendLine("    /// 创 建：" + baseConfigModel.FileConfig.CreateName);
            sb.AppendLine("    /// 日 期：" + baseConfigModel.FileConfig.CreateDate);
            sb.AppendLine("    /// 描 述：" + baseConfigModel.FileConfig.ClassDescription + type);
            sb.AppendLine("    /// </summary>");
        }
        #endregion

        #region GetButtonAuthorizeList 获取按钮授权列表
        /// <summary>
        /// 获取按钮授权列表
        /// </summary>
        /// <returns></returns>
        private List<KeyValue> GetButtonAuthorizeList()
        {
            var list = new List<KeyValue>();
            list.Add(new KeyValue { Key = "btnSearch", Value = "search", Description = "搜索" });
            list.Add(new KeyValue { Key = "btnAdd", Value = "add", Description = "新增" });
            list.Add(new KeyValue { Key = "btnEdit", Value = "edit", Description = "修改" });
            list.Add(new KeyValue { Key = "btnDelete", Value = "delete", Description = "删除" });
            list.Add(new KeyValue { Key = "btnExcel", Value = "excel", Description = "导出" });
            return list;
        }
        #endregion 
        /// <summary>
        /// 获取模块前缀
        /// </summary>
        /// <param name="baseConfigModel"></param>
        /// <returns></returns>
        private string GetModulePrefix(BaseConfigModel baseConfigModel)
        {
            return baseConfigModel.OutputConfig.OutputModule.Replace("Manage", string.Empty).ToLower();
        }
        /// <summary>
        /// 获取基础实体（基础实体类字段）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private string GetBaseEntity(DataTable dt)
        {
            string entity = string.Empty;
            var columnList = dt.AsEnumerable().Select(p => p["TableColumn"].ParseToString()).ToList();

            bool id = columnList.Where(p => p == "Id").Any();
            bool baseIsDelete = columnList.Where(p => p == "BaseIsDelete").Any();
            bool baseVersion = columnList.Where(p => p == "BaseVersion").Any();
            bool baseModifyTime = columnList.Where(p => p == "BaseModifyTime").Any();
            bool baseModifierId = columnList.Where(p => p == "BaseModifierId").Any();
            bool baseCreateTime = columnList.Where(p => p == "BaseCreateTime").Any();
            bool baseCreatorId = columnList.Where(p => p == "BaseCreatorId").Any();

            if (!id)
            {
                throw new Exception("数据库表必须有主键Id字段");
            }
            if (baseIsDelete && baseVersion && baseModifyTime && baseModifierId && baseCreateTime && baseCreatorId)
            {
                entity = "BaseExtensionEntity";
            }
            else if (baseVersion && baseModifyTime && baseModifierId && baseCreateTime && baseCreatorId)
            {
                entity = "BaseModifyEntity";
            }
            else if (baseCreateTime && baseCreatorId)
            {
                entity = "BaseCreateEntity";
            }
            else
            {
                entity = "BaseEntity";
            }
            return entity;
        }
        /// <summary>
        /// 获取保存信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string GetSaveFormCreate(string entity)
        {
            string line = string.Empty;
            switch (entity)
            {
                case "BaseEntity":
                    line = "entity.Create();";
                    break;

                case "BaseCreateEntity":
                    line = "await entity.Create();";
                    break;

                case "BaseModifyEntity":
                    line = "await entity.Create();";
                    break;

                case "BaseExtensionEntity":
                    line = "await entity.Create();";
                    break;
            }
            return line;
        }
        /// <summary>
        /// 获取修改信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string GetSaveFormModify(string entity)
        {
            string line = string.Empty;
            switch (entity)
            {
                case "BaseEntity":
                    line = string.Empty;
                    break;

                case "BaseCreateEntity":
                    line = string.Empty;
                    break;

                case "BaseModifyEntity":
                    line = "await entity.Modify();";
                    break;

                case "BaseExtensionEntity":
                    line = "await entity.Modify();";
                    break;
            }
            return line;
        }
        #endregion
    }
}
